import { getConfirmCode, register, getUserInfo, login,logout } from "@/api/index";

export default {
	namespaced: true,
	actions: {
		//获取验证码
		async getconfirmcode({ commit }, phone) {
			let res = await getConfirmCode(phone);
			if (res.data.code == 200) {
				return Promise.resolve(res.data.data);
			} else {
				return new Error("请求错误");
			}
		},
		//注册
		async postRegister({ commit }, { phone, password, code }) {
			const res = await register({ phone, password, code });
			console.log(res);

			if (res.data.code == 200) return Promise.resolve(200);
			else return new Error("注册失败");
		},

		//登录
		async userlogin({ commit }, { phone, password }) {
			let res = await login({ phone, password });

			if (res.data.code == 200) {
				commit("USERLOGIN", res.data.data.token);
				return Promise.resolve(200);
			} else {
				return Promise.reject(new Error(res.data.message));
			}
		},

		//根据token获取用户信息
		async getuserinfo({ commit }) {
			const res = await getUserInfo();
	
			
			if(res.data.code==200){
				commit("GETUSERINFO", res.data.data);
				return Promise.resolve(200)
			}else{
				commit("GETUSERINFO", res.data.data);
				return Promise.reject(new Error('token过期'))
			}
			
		},

		//退出登录
		async userlogout({commit}) {
			//1通知服务器
            let res=await logout()
            if(res.data.code==200){
                //2删掉仓库里的userinfo和token
                commit('USERLOGOUT')
				return Promise.resolve(200)
            }
			
		},
	},
	mutations: {
		USERLOGIN(state, token) {
			state.token = token;
			localStorage.setItem("Token", token);
		},
		GETUSERINFO(state, userInfo) {
			state.userInfo = userInfo;
		},
        USERLOGOUT(state){
            state.userInfo={}
            localStorage.removeItem("Token")
            state.token=localStorage.getItem("Token")
        }
	},
	state: {
		userInfo: {},
		token: localStorage.getItem("Token"), //第一次如果没有登录过那么就是null 登录后获得token 再下一次登录不发请求就用的本地存储
	},
	getters: {},
};
